<?php
//
// Start buffer
//
ob_start();


//
// PATHs, dont touch here.
//
$DB_PATH = "db/";
$APP_PATH = "app/";
$CONTROLLERS_PATH = $APP_PATH . "controllers/";
$DEFAULT_CONTROLLER_PATH = $CONTROLLERS_PATH . "default.php";
$VIEWS_PATH = $APP_PATH . "views/";
$LAYOUTS_PATH = $APP_PATH . "layouts/";
$PLUGINS_PATH = "plugins/";


//
// Db configuration
//
$APP_DB = "db.php"; 
require_once $DB_PATH . $APP_DB;

//
// Require all plugins
//
foreach ( scandir($PLUGINS_PATH) as $pluginName ) {
  if ($pluginName != "." && $pluginName != "..")
    require_once $PLUGINS_PATH . $pluginName;
}


//
// Now we find out witch page he wants to load
//
if ( array_key_exists("page", $_REQUEST) )
  $desiredPage = $_REQUEST["page"];
else  
  $desiredPage = "index.php";

$desiredPageCompletePath = $CONTROLLERS_PATH . $desiredPage;

if ( file_exists($desiredPageCompletePath) ) {
  //
  // Parse URL QueryString and add to the $_REQUEST var
  //
  $queryString = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
  $query_array = array();
  parse_str($queryString, $query_array);
  
  $_REQUEST = array_merge($_REQUEST, $query_array);
  
  //
  // Requires the default controller before the requested one.
  //
  require_once($DEFAULT_CONTROLLER_PATH);
  require_once($desiredPageCompletePath);
} else {
  //
  // If file does not exist, returns a 404 http error.
  //
  header("HTTP/1.0 404 Not Found");
}


//
// End buffer
//
ob_end_flush();
?>
